<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserCoin extends Model
{
    protected $table = 'user_coin';

    const TYPE_JB = 1;//金币
    const TYPE_ZS = 2;//钻石


    /**
     * [log description]
     * @Author   Jason
     * @DateTime 2017-01-17T19:14:57+0800
     * @param    [type]                   $bussiness_id [ 业务id ]
     * @param    [type]                   $user_id      [ 用户id ]
     * @param    [type]                   $type         [ 金币类型 ]
     * @param    [type]                   $coin         [ 金币值 ]
     * @param    [type]                   $desc         [ 日志描述 ]
     * @return   [type]                                 [description]
     */
    public static function log($bussiness_id, $user_id, $type, $coin, $desc, $key, $flow = 'out')
    {
        // 扣钱必须为负值
        if ($flow == 'out') {
            $coin = -abs($coin);
        }

        $self = new self;
        $self->user_id = $user_id;
        $self->bussiness_id = $bussiness_id;
        $self->type = $type;
        $self->coin = $coin;
        $self->desc = $desc;
        $self->key = $key;
        $self->save();
    }

    public static function totalJb($user_id)
    {
        $coin = self::where('user_id', $user_id)->where('type', self::TYPE_JB)->sum('coin');
        return ($coin > 0) ? $coin : 0;
    }

    public static function totalZs($user_id)
    {
        $coin = self::where('user_id', $user_id)->where('type', self::TYPE_ZS)->sum('coin');
        return ($coin > 0) ? $coin : 0;
    }
    
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * 类型列表
     * @return array
     */
    public static function getTypeList()
    {
        return [
            1 => '小妖币',
            2 => '金币'
        ];
    }

    /**
     * 取得类型
     * @param $type
     * @return mixed|string
     */
    public static function getType($type)
    {
        return isset(self::getTypeList()[$type]) ? self::getTypeList()[$type] : '';
    }

    /**
     * 设置不查询值
     * @return int
     */
    public static function getIndex()
    {
        return 110;
    }
}
